//
//  NSMSearchAssociateController.m
//  NSMKit
//
//  Created by nsm on 2019/5/30.
//  Copyright © 2019 nani. All rights reserved.
//

#import "NSMSearchAssociateController.h"

NSArray *RangesOfSubString(NSString *string,
                           NSString *substring) {
    if (!substring.length || !string.length) return nil;
    
    NSMutableArray *ranges = @[].mutableCopy;
    NSRange searchRange = NSMakeRange(0, string.length);
    NSRange foundRange;
    while (searchRange.location < string.length) {
        searchRange.length = string.length - searchRange.location;
        foundRange = [string rangeOfString:substring
                                   options:NSCaseInsensitiveSearch
                                     range:searchRange];
        if (foundRange.location != NSNotFound) {
            searchRange.location = foundRange.location + foundRange.length;
            [ranges addObject:[NSValue valueWithRange:foundRange]];
        } else {
            break;
        }
    }
    return ranges;
}

NSMutableAttributedString *AttributedText(NSString *text,
                                          NSArray *words) {
    text = SafeString(text);
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
    [attr addAttributes:@{NSForegroundColorAttributeName: COLOR_0,
                          NSFontAttributeName: CustomFont(14)}
                  range:NSMakeRange(0, text.length)];
    
    words = SafeArray(words);
    [words enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *word = SafeString(obj[@"text"]);
        UIColor *color = HexColor(obj[@"color"]);
        NSArray *ranges = RangesOfSubString(text, word);
        for (NSValue *rangeValue in ranges) {
            NSRange range = rangeValue.rangeValue;
            [attr addAttributes:@{NSForegroundColorAttributeName: color} range:range];
        }
    }];
    
    return attr;
}

@interface NSMSearchAssociateCell : NSMTableViewCell
@property (nonatomic, strong) UILabel *titleLabel;
@end

@implementation NSMSearchAssociateCell
- (void)setObject:(id)obj {
    _titleLabel.attributedText = AttributedText(obj[@"title"],
                                                obj[@"words"]);
}

- (void)setupSubviews {
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
    layout.backgroundColor = UIColor.whiteColor;
    layout.myHorzMargin = 0;
    layout.wrapContentWidth = NO;
    layout.wrapContentHeight = YES;
    layout.cacheEstimatedRect = YES;
    layout.padding = UIEdgeInsetsMake(15, 15, 15, 15);
    layout.subviewHSpace = 12;
    layout.gravity = MyGravity_Vert_Center;
    [self.contentView addSubview:layout];
    self.rootLayout = layout;
    
    UILabel *label = [UILabel new];
    label.weight = 1;
    label.wrapContentHeight = YES;
    label.numberOfLines = 1;
    label.font = CustomFont(14);
    label.textColor = UIColor.grayColor;
    [layout addSubview:label];
    _titleLabel = label;
}
@end


@interface NSMSearchAssociateController ()
@end

@implementation NSMSearchAssociateController
@synthesize associateURL = _associateURL ,didSelectAssociateItem = _didSelectAssociateItem;

#pragma mark - lifeCycle

#pragma mark - override

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];    
}

- (void)initSubviews {
    [super initSubviews];
    
    self.tableView.height = kScreenHeight - kNavBarHeight - kSafeAreaBottom;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 44;
    self.tableView.emptySetEnabled = YES;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.urlString = self.associateURL.length?self.associateURL:@"search/associate";
    
    @nsm_weak(self)
    self.tableView.sourceManager.classForCellAtIndexPath = ^Class(NSIndexPath *indexPath) {
        return NSMSearchAssociateCell.class;
    };
    self.tableView.didRefreshingHeaderSuccess = ^(id responseObject) {
        @nsm_strong(self)
        id data = ((NSMResponseObject *)responseObject).data;
        self.tableView.sourceManager.dataArray = [NSMutableArray arrayWithArray:data[@"list"]];
    };
    self.tableView.didRefreshingHeaderEmpty = ^(id responseObject) {
        @nsm_strong(self)
        self.tableView.sourceManager.dataArray = @[].mutableCopy;
        self.tableView.imageForEmptySet = kEmptyDataImage;
        self.tableView.titleForEmptySet = kEmptyDataDesc(((NSMResponseObject *)responseObject).desc);
    };
    self.tableView.didRefreshingHeaderFailure = ^(NSError *error) {
        @nsm_strong(self)
        self.tableView.sourceManager.dataArray = @[].mutableCopy;
        self.tableView.imageForEmptySet = kEmptyDataImage;
        self.tableView.titleForEmptySet = kEmptyDataDesc(error.localizedDescription);
    };
    self.tableView.emptyRefreshingBlock = ^{
        @nsm_strong(self)
        [self.tableView beginRefreshing:RefreshHudCustom];
    };
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    id obj = tableView.sourceManager.dataArray[indexPath.row];
    !self.didSelectAssociateItem?:self.didSelectAssociateItem(obj);
}

#pragma mark - setter/getter

#pragma mark - network
// 这个方法是协议而来
- (void)associateWithKeywords:(NSString *)keywords {
    SEL sel = @selector(reloadAssociate:);
    // 取消之前的请求(如果还有其他perform调用未执行,不管.这里只有自己写的1个perform,不会误伤)
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    // 开启新的任务
    [self performSelector:sel withObject:keywords afterDelay:0.6];
}

- (void)reloadAssociate:(NSString *)keyword {
    self.tableView.parameters = @{@"keyword": SafeString(keyword)};
    [self.tableView beginRefreshing:RefreshHudNone];
}

#pragma mark - method/public

#pragma mark - method/private

#pragma mark - action

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
